﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZGSharp.Layers;

namespace ZGSharp
{
    public class Losses
    {
        public static Tensor MSE(Tensor input, Tensor label)
        {
            Tensor loss = Reduce.mean(TensorMath.Pow((input - label), 2));
            if (double.IsNaN(loss.Avarage())) 
            {
                throw new Exception("Loss Nan");
            }
            return loss;
        }

        public static Tensor CrossEntropy(Tensor input, Tensor label)
        {
            Tensor softmax = Softmax.softmax(input);
            Tensor loss = -label * TensorMath.Log(softmax, Math.E);
            loss = Reduce.sum(loss, new int[] { 1 });
            if (double.IsNaN(loss.Avarage()))
            {
                throw new Exception("Loss Nan");
            }
            return loss;
        }

        public static Tensor SparseCrossEntropy(Tensor input, int[] label, int classNum) 
        {
            Tensor onehot = CommonDef.GetOneHot(label, classNum);
            return CrossEntropy(input, onehot);
        }
    }
}
